//
//  CLAFNTool.m
//  CandleLiving
//
//  Created by Apple on 17/2/28.
//  Copyright © 2017年 Apple. All rights reserved.
//

#import "CLAFNTool.h"

@implementation CLAFNTool
static  CLAFNTool*session;
// 单例
+(instancetype)shareTools{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        //注意： 末尾需要包含 ‘/’
        //一个App通常访问的服务器是固定的
        session = [self manager];
        session.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json",@"text/javascript",@"text/html", nil];
    });
    return session;
}


/**
 *  网路请求工具类
 *
 *  @param url     请求的post url
 *  @param parame  请求携带的参数,没有请写nil
 *  @param success 请求成功时候回调
 *  @param failure 请求失败时候回调
 */
-(void)post:(NSString *)url parameter:(id)parame  success:(void(^)(id responseObject))success failure:(void (^)(NSError* error))failure{
    
    [self POST:url parameters:parame progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        //成功时候
        if (success) {
            success(responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        //失败
        if (error) {
            failure(error);
        }
    }];
}

/**
 发送get请求
 
 @param url 请求get的地址
 @param parame 参数
 @param success 成功的回调
 @param failure 失败的回调
 */
-(void)get:(NSString *)url parameter:(id)parame  success:(void(^)(id responseObject))success failure:(void (^)(NSError* error))failure{
    [self GET:url parameters:parame progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        //成功时候
        if (success) {
            success(responseObject);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        //失败
        if (error) {
            failure(error);
        }
    }];
}

-(void)sendPhoto:(NSString *)url parameter:(id)parame photos:(NSArray *)photos progress:(void(^)(NSProgress * uploadProgress))progress  success:(void(^)(id responseObject))success failure:(void (^)(NSError* error))failure{
    
    [self POST:url parameters:parame constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        // 上传 多张图片
        for(NSInteger i = 0; i < photos.count; i++) {
            NSData * imageData = UIImageJPEGRepresentation([photos objectAtIndex: i], 0.5);
            // 上传的参数名
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            formatter.dateFormat = @"yyyyMMddHHmmss";
            NSString *str = [formatter stringFromDate:[NSDate date]];
            NSString *fileName = [NSString stringWithFormat:@"%@%ld.jpg", str,i];
            NSString *name = [NSString stringWithFormat:@"photo_%ld",i];
            NSLog(@"文件名称=%@",fileName);
            [formData appendPartWithFileData:imageData name:name fileName:fileName mimeType:@"image/jpeg"];
        }
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        if (progress) {
            progress(uploadProgress);
        }
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (success) {
            success(responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure) {
            failure(error);
        }
    }];
}





-(void)postImage:(NSString *)url parameter:(id)parame photos:(NSArray *)photos progress:(void(^)(NSProgress * uploadProgress))progress  success:(void(^)(id responseObject))success failure:(void (^)(NSError* error))failure{
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:url]];
    request.HTTPMethod = @"POST";
    [request setValue:@"multipart/form-data; boundary=kBoundary" forHTTPHeaderField:@"Content-Type"];
    NSData *data = [self setBodydata:photos];
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionUploadTask *task = [session uploadTaskWithRequest:request fromData:data completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        NSDictionary *json =   [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
        NSLog(@"response = %@   error=%@  json=%@",response,error,json);

    }];
    [task resume];
}
- (NSData *)setBodydata:(NSArray *)files
{
    //把文件转换为NSData
//    NSData *fileData = [NSData dataWithContentsOfFile:filePath];
    NSData *fileData = UIImagePNGRepresentation(files.firstObject);
    
    //1.构造body string
    NSMutableString *bodyString = [[NSMutableString alloc] init];
    
    //2.拼接body string
    //(1)access_token
    NSString *boundary = @"kBoundary";
    [bodyString appendFormat:@"--%@\r\n", boundary];//（一开始的 --也不能忽略）
    [bodyString appendFormat:@"Content-Disposition: form-data; name=\"access_token\"\r\n\r\n"];
    [bodyString appendFormat:@"xxxxxx\r\n"];
    
    //(2)status
    [bodyString appendFormat:@"--%@\r\n", boundary];
    [bodyString appendFormat:@"Content-Disposition: form-data; name=\"status\"\r\n\r\n"];
    [bodyString appendFormat:@"带图片的微博\r\n"];
    
    //(3)pic
    [bodyString appendFormat:@"--%@\r\n", boundary];
    [bodyString appendFormat:@"Content-Disposition: form-data; name=\"pic\"; filename=\"file\"\r\n"];
    [bodyString appendFormat:@"Content-Type: image/png\r\n\r\n"];
    
    //3.string --> data
    NSMutableData *bodyData = [NSMutableData data];
    //拼接的过程
    //前面的bodyString, 其他参数
    [bodyData appendData:[bodyString dataUsingEncoding:NSUTF8StringEncoding]];
    //图片数据
    [bodyData appendData:fileData];
    
    //4.结束的分隔线
    NSString *endStr = [NSString stringWithFormat:@"\r\n--%@--\r\n",boundary];
    NSLog(@"结束分割线=%@",bodyString);
    //拼接到bodyData最后面
    [bodyData appendData:[endStr dataUsingEncoding:NSUTF8StringEncoding]];
    
    return bodyData;
}

@end
    

